package com.example.springboottestgit.service;

import com.alibaba.fastjson.JSONObject;
import com.example.springboottestgit.bean.BusinessException;
import com.example.springboottestgit.bean.vo.FileVO;
import com.example.springboottestgit.bean.vo.InputVO;
import com.example.springboottestgit.bean.vo.TenderVO;
import com.example.springboottestgit.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:投标文件-技术要求
 * @author: ZZZ
 */
@Slf4j
@Service
public class SubmitTenderService {

    @Value("${intelligent.match.mode.question.url}")
    private String url;

    //private String url = "http://192.168.80.35:19300/query";

    private Map<Long, List<FileVO>> map = new HashMap<>();

    public void clear() {
        map.clear();
    }

    public void save(long id, long id2, String fileName) {
        List<TenderVO> tenderVOList = new ArrayList<>();
        FileVO<TenderVO> vo = new FileVO();
        vo.setId(id2);
        vo.setAssId(id);
        vo.setFileName(fileName);
        vo.setStatus(0);
        vo.setUploadTime(getDataTime());
        vo.setList(tenderVOList);

        List<FileVO> list = map.get(id);
        if (list != null && list.size() > 0) {
            list.add(vo);
        } else {
            list = new ArrayList<>();
            list.add(vo);
            map.put(id, list);
        }
    }

    public String getDataTime() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String now = dtf.format(LocalDateTime.now());
        return now;
    }

    public void updateStatus(long id, long id2, int status) {
        List<FileVO> list = map.get(id);
        for (FileVO fileVO : list) {
            if (fileVO.getId() == id2) {
                fileVO.setStatus(2);
            }
        }
    }


    public List<FileVO> submitTenderQuery(long id) {
        return map.get(id);
    }

    public void submitTenderDelete(long id, long assId) {
        List<FileVO> list = map.get(assId);
        if (list != null && list.size() > 0) {
            int n = list.size();
            for (int i = n - 1; i >= 0; i--) {
                if (list.get(i).getId() == id) {
                    list.remove(i);
                }
            }
        }
    }

    @Async("myAsync")
    public void question(long id, long id2, String jsonStr) throws InterruptedException {
        LocalDateTime startTime = LocalDateTime.now();
        try {

            //jsonStr = jsonStr.replace("（", "").replace("）", "");
            String[] split = jsonStr.split("\\|");
            List<TenderVO> result = new ArrayList<>();

            for (String s : split) {
                String question = s.trim();
                String output = question(question);
                TenderVO vo = new TenderVO();
                vo.setContent(question);
                vo.setResult(output.contains("不符合") ? false : true);
                vo.setOutput(output);
                result.add(vo);
                updateStatus(id, id2, 0, result);
            }

            String submitTenderName = updateStatus(id, id2, 1, result);

            LocalDateTime endTime = LocalDateTime.now();
            Duration between = Duration.between(startTime, endTime);
            log.info("{} 投标文件技术要求匹配耗时 {} 秒", submitTenderName, between.getSeconds());

        } catch (Exception e) {
            //失败
            List<TenderVO> result = new ArrayList<>();
            String submitTenderName = updateStatus(id, id2, 2, result);
            throw new BusinessException("001001", "投标文件 " + submitTenderName + " 技术要求匹配过程失败");
        }
    }

    public String updateStatus(long id, long id2, int status, List<TenderVO> result) {
        String submitTenderName = "";
        List<FileVO> list = map.get(id);
        for (FileVO fileVO : list) {
            if (fileVO.getId() == id2) {
                fileVO.setStatus(status);
                fileVO.setList(result);
                submitTenderName = fileVO.getFileName();
            }
        }
        return submitTenderName;
    }


    public String question(String question) {
        log.info("技术要求提问：" + question);
        InputVO vo = new InputVO();
        vo.setQuestion(question);
        String param = JSONObject.toJSONString(vo);
        String result = HttpUtils.post(url, param);
        log.info("技术要求回答：" + result);
        result = result.replace("\"", "").trim();
        return result;
    }
}
